package com.ruyuan.eshop.construction.service.impl;

import com.ruyuan.eshop.common.core.PageResult;
import com.ruyuan.eshop.common.utils.ParamCheckUtil;
import com.ruyuan.eshop.construction.domain.dto.AttributeDetailDTO;
import com.ruyuan.eshop.construction.domain.dto.AttributeResultDTO;
import com.ruyuan.eshop.construction.domain.request.AttributeRequest;
import com.ruyuan.eshop.construction.domain.request.QueryAttributeRequest;
import com.ruyuan.eshop.construction.repository.AttributeRepository;
import com.ruyuan.eshop.construction.service.AttributeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 规格服务
 *
 * @author zhonghuashishan
 */
@Service
public class AttributeServiceImpl implements AttributeService {

    @Resource
    private AttributeRepository attributeRepository;

    /**
     * 新增/编辑规格键值接口
     * @param attributeRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AttributeResultDTO saveAttribute(AttributeRequest attributeRequest) {
        // 入参检查
        this.checkAttributeRequestParam(attributeRequest);

        // 保存规格信息
        attributeRepository.saveAttribute(attributeRequest);

        // 返回结果
        return new AttributeResultDTO(Boolean.TRUE);
    }

    /**
     * 新增/编辑规格键值接口
     * @param attributeRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AttributeResultDTO updateAttribute(AttributeRequest attributeRequest) {
        // 入参检查
        this.checkAttributeRequestParam(attributeRequest);

        // 保存规格信息
        attributeRepository.updateAttribute(attributeRequest);

        // 返回结果
        return new AttributeResultDTO(Boolean.TRUE);
    }

    /**
     * 入参检查
     * @param attributeRequest
     */
    private void checkAttributeRequestParam(AttributeRequest attributeRequest) {
        ParamCheckUtil.checkObjectNonNull(attributeRequest);

        // 规格键信息
        AttributeRequest.AttributeKeyRequest attributeKeyRequest = attributeRequest.getAttributeKeyRequest();
        ParamCheckUtil.checkObjectNonNull(attributeKeyRequest);

        // 规格值信息
        List<AttributeRequest.AttributeValueRequest> attributeValueRequests = attributeRequest.getAttributeValueRequests();
        ParamCheckUtil.checkCollectionNonEmpty(attributeValueRequests);
    }

    /**
     * 查询规格键值信息
     * @param queryAttributeRequest
     * @return
     */
    @Override
    public PageResult<AttributeDetailDTO> pageAttribute(QueryAttributeRequest queryAttributeRequest) {
        // 返回结果信息
        return new PageResult<>(attributeRepository.getAttributeDetail(queryAttributeRequest));
    }
}
